package com.xxmw.transaction.common.utils;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xxmw.transaction.conf.ApplicationContextProvider;
import com.xxmw.transaction.model.app.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
public abstract class JWTUtil {

	private static final long EXPIRE_TIME = 3600000*24;

	private static String SECRET = IdWorker.get32UUID();

	static {
		String activeProfile = ApplicationContextProvider.getApplicationContext().getEnvironment().getActiveProfiles()[0];
		if ("dev".equals(activeProfile) || "test".equals(activeProfile)) {
			SECRET = "1d2d2bfb329b456fb28f38e363bec3df";
		}
	}

	/**
	 * 生成token
	 * @param user user对象JSONString
	 * @return
	 */
	public static String generate(String user) {
		Date expire = new Date(System.currentTimeMillis() + EXPIRE_TIME);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("alg", "HS256");
		map.put("typ", "JWT");

		return JWT.create().withIssuer("znkj").withSubject(user).withHeader(map).withKeyId(IdWorker.getIdStr()).withIssuedAt(new Date()).withExpiresAt(expire).sign(Algorithm.HMAC256(SECRET));
	}

	/**
	 * 验证并获取subject
	 * @param appToken
	 * @return
	 */
	public static String verity(String appToken) {
		Algorithm algorithm = Algorithm.HMAC256(SECRET);
		JWTVerifier verifier = JWT.require(algorithm).build();
		DecodedJWT verify = verifier.verify(appToken);
		return verify.getSubject();
	}

	public static User getUser (String appToken) {
		return JSON.parseObject(verity(appToken), User.class);
	}
}
